﻿using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RbacPermissionManage.Application;
using RbacPermissionManage.Application.Admins;
using RbacPermissionManage.Application.Admins.Dto;
using RbacPermissionManage.DoMain;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using Microsoft.AspNetCore.HttpOverrides;
using CSRedis;

namespace RbacPermissionManage.WebAPI.Controllers
{
    /// <summary>
    /// 管理员控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class AdminController : ControllerBase
    {
        //管理员接口
        private readonly IAdminServices adminServices;
        private readonly ICaptcha _captcha;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly CSRedisClient redis;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="adminServices"></param>
        public AdminController(IAdminServices adminServices, ICaptcha captcha, IHttpContextAccessor httpContextAccessor)
        {
            this.adminServices = adminServices;
            this._captcha = captcha;
            this.httpContextAccessor = httpContextAccessor;
            redis = new CSRedisClient("127.0.0.1:6379");
        }


        /// <summary>
        /// 显示测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get()
        {
            var ipAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            return Ok(ipAddress);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="registerDto">注册DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> RegisterAsync(RegisterDto registerDto)
        {
            var result=await adminServices.RegisterAsync(registerDto);
            return Ok(result);
        }

        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="createDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateAsync(AdminCreateDto createDto)
        {
            ResultDto dto = await adminServices.CreateAsync(createDto);
            return Ok(dto);
        }

        /// <summary>
        /// 根据Id获取adminDto
        /// </summary>
        /// <param name="AdminId">管理员Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> BackfillAsync(int AdminId)
        {
            return Ok(await adminServices.BackfillAsync(AdminId));
        }

        /// <summary>
        /// 修改管理员
        /// </summary>
        /// <param name="updateDto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateAsync(AdminUpdateDto updateDto)
        {
            ResultDto dto = await adminServices.UpdateAsync(updateDto);
            return Ok(dto);
        }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Captcha(string id)
        {
            redis.Del("Captcha");
            var info = _captcha.Generate(id);
            redis.Set("Captcha", info.Code);
            // 有多处验证码且过期时间不一样，可传第二个参数覆盖默认配置。
            //var info = _captcha.Generate(id,120);
            var stream = new MemoryStream(info.Bytes);
            return File(stream, "image/gif");
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> LoginAsync(LoginDto loginDto)
        {
            var Yam = redis.Get("Captcha");
            if(Yam.ToLower()==loginDto.ValidateCode.ToLower())
            {
                string strToken = CreateTokenString(loginDto.UserName);
                var dto = await adminServices.LoginAsync(loginDto);
                return Ok(new
                {
                    code = dto.Code,
                    msg = dto.Message,
                    token = strToken
                });
            }
            else
            {
                return Ok(new
                {
                    code = -1,
                    msg = "验证码错误"
                });
            }
        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString(string account)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //设置jwt的claim
            Claim[] claims = new Claim[] {
                new Claim(ClaimTypes.Name,account),//账号
                //new Claim("id",id),//账号
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }


        /// <summary>
        /// 查询分页显示管理员列表
        /// </summary>
        /// <param name="searchDto"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAdminAsync([FromQuery]AdminSearchDto searchDto, int pageIndex=1, int pageSize=10)
        {
            try
            {
                var list = await adminServices.GetAdminAsync(searchDto, pageIndex, pageSize);
                return Ok(new
                {
                    Code=Code.Success,
                    Data = new
                    {
                        PageData=list.Data.Item2,
                        Count=list.Data.Item1
                    }
                });
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="AdminId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DeleteAsync(int AdminId)
        {
            ResultDto dto=await adminServices.DeleteAsync(AdminId);
            return Ok(dto);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="adminIds"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDelAsync(List<int> adminIds)
        {
            ResultDto dto = await adminServices.BatchDelAsync(adminIds);
            return Ok(dto);
        }
    }
}
